package com.uni.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uni.base.RestResponse;
import com.uni.pojo.*;
import com.uni.service.FileUploadService;
import com.uni.service.ProductService;
import com.uni.service.ProviderService;
import com.uni.utils.PageUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/product")
public class ProductAdminController {
    @Autowired
    ProductService productService;
    @Autowired
    ProviderService providerService;

    @Value("${uni.web.imgSavePath}")
    String imgSavePath;

    @Autowired
    FileUploadService fileUploadService;

    @PostMapping("/query")
    public String queryProduct(@RequestBody(required = false) Map<String, String> map){
        int pageNow = map == null ? 1 : Integer.parseInt(map.getOrDefault("pageNow", "1"));
        PageHelper.startPage(pageNow, 6);
        List<Product> products = productService.getProductWithProviderBySome(map);
        PageInfo pageInfo = PageUtil.setPageInfo(pageNow, 6, products);
        List<Prodtype> prodtypes = productService.getAllProdType();
        return RestResponse.ok(new HashMap<String, Object>() {{
            put("pageInfo", pageInfo);
            put("prodtypes", prodtypes);
        }}).toJSONString();
    }
    @PostMapping("/update")
    public String updateProduct(@RequestBody Map<String, Object> map){
        if(map == null)
            return RestResponse.fail("接收到的参数为空").toJSONString();
        String type = (String) map.getOrDefault("type", "");
        // 标记结果
        int i = 0;
        // 批量操作
        if("downs".equals(type) || "ups".equals(type)){
            List<Long> prodId = (List<Long>) map.getOrDefault("prodId", null);
            if (type.equals("downs")) {
                i = productService.takeThemDown(prodId);
            }
            else if(type.equals("ups")){
                i = productService.takeThemUp(prodId);
            }
        }
        else if("down".equals(type) || "up".equals(type)){
            Long prodId = Long.parseLong((String) map.getOrDefault("prodId", null));
            if (type.equals("down")) {
                i = productService.takeItDown(prodId);
            }
            else if(type.equals("up")){
                i = productService.takeItUp(prodId);
            }
        }
        return i > 0 ? RestResponse.ok("操作成功!").toJSONString() : RestResponse.fail("未修改到任何商品").toJSONString();
    }
    @PostMapping("/query/{prodId}")
    public String queryProductById(@PathVariable Long prodId){
        Product product = productService.getProductWithProviderById(prodId);
        return product == null ? RestResponse.fail("未查询到该商品").toJSONString()
                : RestResponse.ok(product).toJSONString();
    }


    @PostMapping("/update/{prodId}")
    public String updateProdcutInfo(@PathVariable Long prodId, Product prod){
        // 图片单独处理
        Product oldProduct = productService.getProductWithProviderById(prodId);
        prod.setImg(oldProduct.getImg());
        // 执行修改业务
        int i = productService.modifyProductById(prod);
        return i == 2 ? RestResponse.ok("修改商品信息成功!").toJSONString()
                : RestResponse.fail("修改商品信息失败").toJSONString();
    }
    @PutMapping("/update/{prodId}")
    public String updateProductImg(@RequestParam String base64url, @PathVariable Long prodId) throws IOException {
        Product prod = productService.getProductWithProviderById(prodId);
        FileUploadResult uploadResult = fileUploadService.upload(base64url, prodId);
        int i = 0;
        if(FileUploadService.SUCCESS.equals(uploadResult.getResponse())){
            prod.setImg(uploadResult.getName());
            i = productService.modifyProductById(prod);
        }
        return i > 0 ? RestResponse.ok("修改成功!").toJSONString()
                : RestResponse.fail("修改失败.").toJSONString();
    }

    /* 添加商品 */
    @PostMapping("/add")
    public String addProduct(Product product){
        Product prod = productService.addProduct(product);
        FileUploadResult result = new FileUploadResult("error");
        if(prod != null) {
            result = fileUploadService.upload(prod.getImg(), prod.getId());
            prod.setImg(result.getName());
            prod.setProvider(new Provider() {{setId(product.getProvider().getId());}});
            int i = productService.modifyProductById(prod);
            if(i < 1)
                result.setStatus("error");
        }
        return "error".equals(result.getStatus()) ?
                RestResponse.fail("添加商品失败.").toJSONString()
                : RestResponse.ok("添加商品成功!").toJSONString();
    }


}
